<?php

/**
 * 邮箱检查
 */
if (! function_exists('is_email')) {
    function is_email($email)
	{
		return  filter_var($email, FILTER_VALIDATE_EMAIL);
	}
}

/**
 * 手机号检查
 */
if (! function_exists('is_phone_number')) {
	function is_mobile($mobile)	
	{
		if (!is_numeric($mobile)) {  
        	return false;  
    	}  
    	return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false; 
	}
}

/**
 * 格式化返回数据
 */
if (! function_exists('build_result')) {
	function build_result($data, $code = 0, $message = 'success')
	{
		static $errorCodes;
		$result = array();
		$result['code'] = $code;
		$result['data'] = $data;
		$result['message'] = $message;
		
		if($code !== 0 ) {
			if(empty($errorCodes)){
				$errorCodes = require __DIR__ . '/errorcodes.php';
			}
			if(isset($errorCodes[$code]))$result['message'] = $errorCodes[$code] . '[' . $message . ']';
		}

		if((int)$code > 20000) {
			$result = array(
					'code' => 0,
					'message' => 'success',
					'data' => $result
				);
		}

		header("Access-Control-Allow-Origin: http://localhost:8080");
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        header("Access-Control-Allow-Methods:POST, GET, OPTIONS");
        header("Access-Control-Allow-Credentials: true");
 

		return $result;
	}
}

/**
 * 密码生成规则
 */
if(! function_exists('get_password') ){
	function get_password($str, $suffix) {
		return ''===$str ? '' : md5(sha1($str).$suffix);
	}
}

/**
 * 用户登录凭证生成规则
 */
if(! function_exists('create_token')) {
	function create_token($str) {
		return md5($str.sha1(time()).sha1(mt_rand()));
	}
}

/**
 * 用户注册生成激活码（纯数字）
 */
if(! function_exists('build_activation_key_number')) {
	function build_activation_key_number(){
    	$randStr = str_shuffle('1234567890');
    	$rand = substr((int)$randStr,0,6);
    	return $rand;
	}
}

/**
 * 生成随机字符创
 */
if(! function_exists('generate_nonce_str')) {
	function generate_nonce_str($length = 16) {
	    // 密码字符集，可任意添加你需要的字符
	    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	    $str = "";
	    $count = strlen($chars);
	    for($i = 0; $i < $length; $i++) {
	        $str .= $chars[mt_rand(0,  $count - 1)];
	    }
	    return $str;
	}
}

/**
 * 生成GUID
 */
if(!function_exists('GUID')) {
	function GUID()
	{
		return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
	}
}

/**
 * 时间戳格式化
 *
 * @param int $time
 * @return string 完整的时间显示
 */
if ( !function_exists('time_format') ) {
	function time_format($time = NULL, $format = 'Y-m-d H:i') {
	    if (empty($time)) return '';

	    $time = ($time === NULL) ? NOW_TIME : intval($time);
	    return date($format, $time);
	}
}

if (!function_exists('minut_format') ) {
	function day_format($time = NULL) {
	    return time_format($time, 'Y-m-d H:i');
	}	
}

if ( !function_exists('day_format') ) {
	function day_format($time = NULL) {
	    return time_format($time, 'Y-m-d');
	}	
}

/**
 * 拼接icon链接
 */
if ( !function_exists('get_project_icon_url')) {
	function get_project_icon_url($token, $templateName)
	{
		return env('GAME_HOST') . '/play/tpl_' . $templateName . '/' . $token . '/icon.png';
	}
}

/**
 * 拼接游戏预览链接
 */
if ( !function_exists('get_project_preview_url')) {
	function get_project_preview_url($token, $templateName)
	{
		return env('GAME_HOST') . '/play/tpl_' . $templateName . '/' . $token . '/?openid=otuWJjvQKhb9nn1xL8v-IRrgxct8';
	}
}

/**
 * 获取游戏编辑链接
 */
if ( !function_exists('get_project_edit_url')) {
	function get_project_edit_url($token, $templateName)
	{
		return env('GAME_HOST') . '/app/proxy/' . time() . '/' . $templateName  . '/' . $token . '/?openid=otuWJjvQKhb9nn1xL8v-IRrgxct8';
	}
}

/**
 * 获取游戏二维码链接
 */
if (!function_exists('get_project_qrcode_url')) {
	function get_project_qrcode_url($token, $templateName)
	{
		return env('GAME_HOST') . '/app/proxy/' . time() . '/' . $templateName  . '/' . $token . '/';
	}
}

/**
 * 获取模版icon
 */
if ( !function_exists('get_template_icon_url')) {
	function get_template_icon_url($path)
	{
		return env('GAME_HOST') . $path;
	}
}

/**
 * 拼接模版预览链接
 */
if ( !function_exists('get_template_preview_url')) {
	function get_template_preview_url($token, $templateName)
	{
		return env('GAME_HOST') . '/demo/' . $templateName . '/?appid=' . $token . '&openid=otuWJjvQKhb9nn1xL8v-IRrgxct8';
	}
}

/**
 * 获取模版二维码链接
 */
if (!function_exists('get_template_qrcode_url')) {
	function get_template_qrcode_url($token, $templateName)
	{
		return env('GAME_HOST') . '/demo/' . $templateName . '/?appid=' . $token;
	}
}

/**
 * 获取背景音乐链接
 */
if (!function_exists('get_bgmusic_url')) {
	function get_bgmusic_url($path)
	{
		return env('RES_HOST') . '/' . $path;
	}
}

/**
 * 判断是否为线上
 */
if ( !function_exists('is_online')) {
	function is_online()
	{
		return app()->environment() == 'production' ? true : false;
	}
}


/**
 * 背景音乐列表
 */
if ( !function_exists('build_project_info')) {
	function build_bgmusic_info($list)
	{
		$ret = array();
		foreach ($list as $key => $item) {
			$tmp['id'] = $item['id'];
			$tmp['title'] = $item['title'];
			$tmp['path'] = get_bgmusic_url($item['path']);
			$tmp['is_select'] = isset($item['is_select']) ? $item['is_select'] : 0;
			$ret[] = $tmp;
		}
		return $ret;
	}
}


/**
 * 项目信息格式化
 */
if ( !function_exists('build_project_info') ) {
	function build_project_info($data)
	{
		$ret = array();
		foreach ($data as $key => $item) {
			$tmpgame = array();
			$tmpgame['title']   		= $item['title'];
            $tmpgame['desc']    		= $item['desc'];
            $tmpgame['token']   		= $item['token'];
            $tmpgame['status']  		= $item['status'];
            $tmpgame['raffletype']  	= $item['raffletype'];
            $tmpgame['cover_url'] 		= get_project_icon_url($item['token'], $item['name']);
            $tmpgame['preview_url']		= get_project_preview_url($item['token'], $item['name']);
            $tmpgame['qrcode_url']		= get_project_qrcode_url($item['token'], $item['name']);
            // $tmpgame['edit_url']		= get_project_edit_url($item['token'], $item['name']);
            $tmpgame['create_time'] 	= day_format($item['create_time']);
            $tmpgame['modify_time'] 	= day_format($item['modify_time'] ? $item['modify_time'] : $item['create_time']);

            //下线时间
            $caseStatus = $item['status'];
            if($item['endtime'] <= time() ) $caseStatus = 1;
            $tmpgame['status']  = $caseStatus;
            $tmpgame['endtime'] = time_format($item['endtime']);

            $ret[] = $tmpgame;
		}
		return $ret;
	}
}


/**
 * 模版信息格式化
 */
if ( !function_exists('build_template_info') ) {
	function build_template_info($data)
	{
		$ret = array();
		foreach ($data as $key => $item) {
			$template = array();
			$template['name'] 			= $item['name'];
			$template['title'] 			= $item['title'];
			$template['desc'] 			= $item['desc'];
			$template['cover'] 			= $item['icon_url'];
			$template['preview_url']	= get_template_preview_url($item['apptoken'], $item['name']);
			$template['qrcode_url']		= get_template_qrcode_url($item['apptoken'], $item['name']);
			$template['raffletypes']	= $item['raffletypes'];
			$ret[] = $template;
		}
		return $ret;
	}
}


/**
 * 获取项目相对路径
 */
if( !function_exists('get_app_dir'))
{
	function get_app_dir( $token )
	{
		$app_folder = config('base_path') . '../' . env("APP_PATH");
		return $app_folder . substr($token, 0, 1) . '/' . substr($token, 1, 1) . '/' .$token;
	}
}

/**
 * 获取模版相对路径
 */
if( !function_exists('get_template_dir'))
{
	function get_template_dir($template_name)
	{
		$template_folder = config('base_path') . '../' . env('TEMPLATE_PATH');
		return $template_folder;
	}
}

/**
 * 获取资源的相对路径
 */
if (!function_exists('get_resource_dir')) {
	function get_resource_dir()
	{
		return config('base_path') . '../' .env('RESOURCE_PATH');
	}
}

/**
 * 创建目录
 */
if( !function_exists('create_path'))
{
	function create_path($dir)
	{
		if (!is_dir($dir)) {
	        if (!mkdir($dir, 0777, true)) {
	            return false;
	        }
	    }
	    return true;
	}
}

/**
 * 拷贝目录
 */
if( !function_exists('copy_dir'))
{
	function copy_dir($sur_dir, $to_dir)
	{
		$sur_dir = rtrim($sur_dir,'/').'/';
		$to_dir = rtrim($to_dir,'/').'/';
		if (!file_exists($sur_dir))
		{
			return  false;
		}
		if (!file_exists($to_dir))
		{
			create_path($to_dir);
		}
		$file = opendir($sur_dir);
		while ($fileName = readdir($file))
		{
			$file1 = $sur_dir .'/'.$fileName;
			$file2 = $to_dir .'/'.$fileName;
			if ($fileName != '.' && $fileName != '..')
			{
				if (is_dir($file1))
				{
					copy_dir($file1, $file2);
				}
				else
				{
					copy($file1, $file2);
				}
			}
		}
		closedir($file);
		return true;
	}
}

/**
 * set global appid for sharding
 */
if( !function_exists('set_sharding_info')) {
	function set_sharding_info($appid = 0, $is_select = 0)
	{
		$GLOBALS['appid'] = $appid;
		$GLOBALS['is_select'] = $is_select;
	}
}

/**
 * 获取数据库名称
 */
if( !function_exists('get_db_config')) 
{
	function get_connection_name($db_name, $is_sharding = 0)
	{
		$appid = isset($GLOBALS['appid']) ? $GLOBALS['appid'] : 0;
		$is_select = isset($GLOBALS['is_select']) ? $GLOBALS['is_select'] : 0;
		

		if(config('INIT_APPID') > $appid || !$is_sharding) {
			if($is_select) {
				$db_name = $db_name . '_slave';
			}
		} else {
			$GLOBALS['isSharding'] = isset($GLOBALS['isSharding']) ? $GLOBALS['isSharding'] : array();
			if(isset($GLOBALS['isSharding'][$appid])) {
				$db_name = $GLOBALS['isSharding'][$appid];
			} else {
				$db_name .= '_' . ($appid%16);
				$GLOBALS['isSharding'][$appid] = $db_name;
			}
		}
		return $db_name;
	}
}

/**
 * 批量获取随机数
 */
if( !function_exists('generate_nonce_number_array')) {
	function generate_nonce_number_array($count, $length){
	    $randnum = 999999;
	    for ($i = $count; $i>0; $i--) {
	        $randnum -= mt_rand(1, 9);
	        $data[] = $randnum . generate_nonce_number($length);
	    }
	    unset($randnum);
	    return $data;
	}
}

/**
 * 批量获取随机数
 */
if( !function_exists('generate_nonce_number_array')) {
	function generate_nonce_number($length = 8) {
	    $startnumber = pow(10, $length-1);
	    $endnumber = pow(10, $length) - 1;
	    return mt_rand($startnumber, $endnumber);
	}
}